<template>
	<view class="chat">
		<view class="prompt">
			<u-notice-bar text="官方提醒：请勿轻信不明跳转链接、二维码支付及其他联系方式，如脱离小竹财税平台交易，支付打款。资金安全、纠纷处理、完善交付将均不受保障！"></u-notice-bar>
		</view>

		<scroll-view scroll-y="true" class="chat-list" :style="{height: upShow ? upScrollHeight : scrollHeight}"
			:scroll-with-animation="true" :scroll-top="scrollTop">
			<view @click="upShow = false">
				<view class="history">
					<u-button v-show="curMessageList.length >= 30" type="primary" :plain="true" text="查看历史" shape="circle"
						@click="moreMessage"></u-button>
				</view>
				<chatlist class="dialogue-box-content" :curMessageList="curMessageList" :conversationObj="conversationObj">
				</chatlist>

			</view>
		</scroll-view>
		<view class="chat-input">
			<view v-if="wechatShow" class="wechat-area">
				<view class="left-area">
					<text class="cuIcon-close" @click="closeWechat"></text>
					<image src="https://xzcs-public-files.oss-cn-beijing.aliyuncs.com/static/New-my/weixinlogo.png"
						class="wechat-img"></image>
					<text class="wechat-text">关注公众号，时刻获取消息通知</text>
				</view>
				<view class="right-area" @click="goWechat">
					去开启
				</view>
			</view>
			<view class="input">
				<u--input v-model="messageText" placeholder="请输入内容" border="none" shape="circle" :customStyle="{
					width: messageText ? '500rpx' : '530rpx',
					height: '70rpx',
					background: '#F6F6F6',
					borderRadius: '168rpx',
					marginRight: '28rpx',
					paddingLeft: '35rpx'
				}" @focus="upShow = false" confirmType="发送" @confirm="sendMessage(1)"></u--input>
				<view :style="{width: messageText ? '100rpx' : '0'}" class="but" @click="sendMessage(1)">
					发送
				</view>
				<u-icon name="plus-circle" :size="messageText ? '0' : '38'" @click="showUp"></u-icon>
			</view>
			<view v-show="upShow" class="up">
				<u-grid :border="false" col="5">
					<u-grid-item @click="ChooseImage">
						<u-icon name="photo-fill" :size="34"></u-icon>
						<text class="grid-text">图片</text>
					</u-grid-item>
					<u-grid-item v-if="userInfo && userInfo.is_server == 1" @click="shopShow = true">
						<u-icon name="bag-fill" :size="34"></u-icon>
						<text class="grid-text">商品</text>
					</u-grid-item>
					<u-grid-item v-if="userInfo && userInfo.is_server == 1" @click="orderShow = true">
						<u-icon name="file-text-fill" :size="34"></u-icon>
						<text class="grid-text">订单</text>
					</u-grid-item>
				</u-grid>
			</view>
		</view>

		<u-popup :show="shopShow" mode="bottom" @close="close" :closeable="true" @open="shopOpen">
			<scroll-view scroll-y="true" style="height: 800rpx;background-color: #F6F6F6;" @scrolltolower="shopOpen">
				<view class="shop-list">
					<view class="shop-title">
						发送商品
					</view>
					<view v-for="(item,index) in shopList" :key="index" class="shop-item">
						<image :src="item.pic" mode="aspectFill"></image>
						<view class="info">
							{{item.name}}
							<view class="text">
								<template v-if="goodsIndex != index">
									￥{{ item.price }}
								</template>
								<template v-else>
									<u-number-box v-model="item.price" min="0" button-size="26" step="1"
										decimal-length="2"></u-number-box>
								</template>
								<view class="xg" @click="editGoods(index)">
									{{ goodsIndex == index ? "完成" : "修改" }}
								</view>
							</view>
						</view>
						<view class="money">
							<view>￥{{item.price}}</view>
							<u-button type="primary" shape="circle" :plain="true" :hairline="true" text="发送" size="mini"
								:customStyle="{width: '108rpx',height: '50rpx'}" @click="sendMessage('shop', item)"></u-button>
						</view>
					</view>
				</view>
			</scroll-view>
		</u-popup>

		<u-popup :show="orderShow" mode="bottom" @close="close" :closeable="true" @open="orderOpen">
			<scroll-view scroll-y="true" style="height: 800rpx;background-color: #F6F6F6;" @scrolltolower="orderOpen">
				<view class="shop-list">
					<view class="shop-title">
						发送订单
					</view>
					<view v-for="(item,index) in orderList" :key="index" class="shop-item">
						<image :src="item.shopinfo.pic" mode="aspectFill"></image>
						<view class="info">
							{{item.shopinfo.name}}
							<view class="text">
								<template v-if="orderIndex != index">
									￥{{item.money}}
								</template>
								<template v-else>
									<u-number-box v-model="item.money" min="0" button-size="26" step="1"
										decimal-length="2"></u-number-box>
								</template>
								<view class="xg" @click="xg(index)">
									{{orderIndex == index ? '完成' : '修改'}}
								</view>
							</view>
						</view>
						<view class="money">
							<u-button type="primary" shape="circle" :plain="true" :hairline="true" text="发送" size="mini"
								:customStyle="{width: '108rpx',height: '50rpx'}" @click="sendMessage('order', item)"></u-button>
						</view>
					</view>
				</view>
			</scroll-view>
		</u-popup>
	</view>
</template>

<script>
	import sApi from "@/api/service.js"
	import homeApi from "@/api/home.js"
	import chatlist from "@/pages/message/components/chatList.vue"
	export default {
		components: {
			chatlist
		},
		data() {
			return {
				conversationID: 0,
				userInfo: null,

				curMessageList: [],
				historyConfig: {},
				conversationObj: null,

				messageText: '',
				imgUrl: '',

				upShow: false,
				switchSubmitType: true,
				scrollTop: 0,
				shopShow: false,
				orderShow: false,
				shopPage: 1,
				shopList: [],
				orderList: [],
				orderIndex: null,

				wechatShow: true,
				upScrollHeight: 'calc(100vh - 468rpx)',
				scrollHeight: 'calc(100vh - 288rpx)',

				bodyHidden: true, // 用户是否在当前页
				goodsIndex: null
			};
		},
		onLoad(query) {
			if (query.id)
				this.conversationID = query.id + ''
			else
				uni.navigateBack({
					delta: 1
				});
		},
		onReady() {
			this.init()
		},
		onShow() {
			this.bodyHidden = true
			if (this.conversationID)
				this.$store.state.zim.sendConversationMessageReceiptRead(
					this.conversationID,
					0
				);
			this.userInfo = this.$store.state.userInfo
			if (uni.getStorageSync('userInfo').official_openid) {
				this.wechatShow = false
			}
		},
		onHide() {
			this.bodyHidden = false
		},
		onUnload() {
			this.bodyHidden = false
		},
		computed: {},
		watch: {

		},
		methods: {
			
			//修改商品价格
			async editGoods(index) {
				if (this.goodsIndex == index) {
					let item = this.shopList[index];
					let params = {
						id: item.id,
						price: item.price,
					};
					const res = await sApi.change_price(params);
					if (res.code == 1) {
						uni.showToast({
							title: "修改成功",
							icon: "none",
						});
						this.goodsIndex = null;
					}
				} else {
					this.goodsIndex = index;
				}
			},


			//关闭公众号
			closeWechat() {
				this.wechatShow = false
				this.upScrollHeight = 'calc(100vh - 380rpx)'
				this.scrollHeight = 'calc(100vh - 200rpx)'
			},

			//跳转关注公众号
			goWechat() {
				uni.navigateTo({
					url: '/pagesPersonal/attentionWechat/attentionWechat'
				})
			},

			//获取全部需求类型
			getAllCate() {
				homeApi.getServiceCate().then(res => {
					if (res.code === 1) {
						this.cateList = res.data
						console.log(this.cateList)
					} else {
						this.$common.msgShow(res.msg)
					}
				})
			},

			async init() {
				this.userInfo = this.$store.state.userInfo
				let that = this;
				// 注册监听“收到单聊消息”的回调
				this.$store.state.zim.on("receivePeerMessage", function(zim, zimRes) {
					console.log("收到消息···········", zim, zimRes);
					let {
						fromConversationID,
						messageList
					} = zimRes;
					if (fromConversationID == that.conversationID) {
						that.curMessageList.push(...messageList);
						if (that.bodyHidden)
							that.$store.state.zim.sendConversationMessageReceiptRead(
								that.conversationID,
								0
							);
						that.$nextTick(() => {
							that.setScrollTop()
						})
					}

				});

				this.$store.state.zim.on(
					"conversationMessageReceiptChanged",
					function(zim, zimRes) {
						// 把自己发的消息标记为已读
						// curMessageList[messageItem].receiptStatus这JB变量tmd怎么是只读的
						// for (let messageItem of that.curMessageList) {
						// 	console.log(messageItem)
						// 		messageItem.receiptStatus = 2;
						// }
						that.curMessageList = that.curMessageList.map(({
							...item
						}) => {
							return {
								...item,
								receiptStatus: 2
							}
						})
						sApi.check_read({
							to_userid: that.conversationID,
						});
					}
				);

				let to_zim_userid = uni.getStorageSync("to_zim_userid");
				if (to_zim_userid && to_zim_userid != this.userInfo.id + "") {
					this.send_message(to_zim_userid);
				} else {
					uni.removeStorageSync("to_zim_userid");
				}

				this.queryUsersInfo()
				this.getHistoryMessage();
			},

			// 建立聊天关系
			async send_message(to_zim_userid) {
				if (this.userInfo.id + "" == to_zim_userid) return;
				const res = await sApi.send_message({
					userid: this.userInfo.id + "",
					touserid: to_zim_userid + "",
				});
				if (res.code == 1) {
					setTimeout(() => {
						uni.removeStorageSync("to_zim_userid");
					}, 800);
				}
			},

			// 发送消息
			sendMessage(messageType, sItem = null) {
				wx.requestSubscribeMessage({
				  tmplIds: ['FDa3cltqtpSJ-1enjsx3vym6nRR8r1CDMpJQkUpr2DQ', 'maUnBJPtl6zy5bnMvtfPHDJtJbSkwhywbg7FUjoM3Vc'],
				  success (res) {
						console.log(res)
				  }
				})
				if (!this.switchSubmitType) return;
				if (messageType == 1 && !this.messageText) return;
				this.switchSubmitType = false;
				let that = this
				this.$store.state.zim.clearConversationUnreadMessageCount(
					this.conversationID,
					0
				);

				let config = {
					priority: 1, // 设置消息优先级，取值为 低：1（默认），中:2，高：3
					hasReceipt: true,
				};

				let notification = {
					onMessageAttached: function(message) {
						// todo: Loading
					}
				}
				let extendedData = {
					type: messageType,
				};
				let message = "";
				if (messageType == 1) message = this.messageText;
				else if (messageType == "order") {
					message = "[订单]";
					extendedData.order_no = sItem.order_no;
					extendedData.money = sItem.money;
					extendedData.pic = sItem.shopinfo.pic.split(",")[0];
					extendedData.name = sItem.shopinfo.name;
				} else if (messageType == "shop") {
					message = "[" + sItem.name + "]";
					extendedData.id = sItem.id;
					extendedData.price = sItem.price;
					extendedData.pic = sItem.pic.split(",")[0];
					extendedData.name = sItem.name;
				} else if (messageType == 11) {
					message = that.imgUrl;
				} else if (messageType == 111) {
					message = that.imgUrl;
				} else if (messageType == "file") {
					message = that.fileName;
					extendedData.fileUlr = that.fileUrl;
				}

				let messageTextObj = {
					type: 1,
					message: message,
					extendedData: JSON.stringify(extendedData),
				};

				this.$store.state.zim.sendMessage(messageTextObj, this.conversationID, 0, config, notification)
					.then(function(sendRes) {
						// 发送成功
						console.log(message)
						that.switchSubmitType = true;
						that.curMessageList.push(sendRes.message);
						that.messageText = ''
						that.close()
						// 消息记录到后台
						that.recordmessage(sendRes);
					})
					.catch(function(err) {
						// 发送失败
					});
			},

			async recordmessage(send) {
				let sendRes = {
					...send.message
				};

				if (sendRes.message) {
					sendRes.message = sendRes.message.replace(/%/g, "%25");
					sendRes.message = sendRes.message.replace(/\+/g, "%2B");
					sendRes.message = sendRes.message.replace(/</g, "%3C");
					sendRes.message = sendRes.message.replace(/>/g, "%3E");
				} else {
					return;
				}
				sendRes.extendedData = JSON.parse(sendRes.extendedData);
				const res = await sApi.sendmessage({
					type: "1",
					message: JSON.stringify(sendRes),
					to_userid: sendRes.conversationID,
					username: this.userInfo.is_server == 1 ?
						this.userInfo.service_info.name : this.userInfo.nickname,
				});
				let that = this
				if (res.code == 1)
					setTimeout(() => {
						sApi.delay_pushmessage({
							id: res.data,
							to_userid: that.conversationID
						});
					}, 5000);
				this.$nextTick(() => {
					this.setScrollTop()
				})
			},

			// 获取对方用户信息
			queryUsersInfo() {
				let that = this
				this.$store.state.zim.queryUsersInfo([this.conversationID], {
						isQueryFromServer: false
					})
					.then(function({
						userList,
						errorUserList
					}) {
						// 操作成功
						console.log('queryUsersInfo', userList, errorUserList)
						that.conversationObj = userList[0]
						uni.setNavigationBarTitle({
							title: that.conversationObj.baseInfo.userName
						});
					})
					.catch(function(err) {
						// 操作失败
					});
			},

			// 获取历史记录
			getHistoryMessage() {
				if (!this.conversationID) return;
				this.curMessageList = [];
				let conversationID = this.conversationID;
				let conversationType = 0;

				// 从后往前获取会话历史消息，每次获取 30 条
				this.historyConfig = {
					nextMessage: null, // 首次获取时 nextMessage 为 null
					count: 30,
					reverse: true,
				};

				let that = this;

				this.$store.state.zim
					.queryHistoryMessage(
						conversationID,
						conversationType,
						this.historyConfig
					)
					.then(({
						messageList
					}) => {
						that.curMessageList.push(...messageList);
						that.$nextTick(() => {
							that.setScrollTop()
						})
						// 清楚和对方的消息未读数
						that.$store.state.zim.clearConversationUnreadMessageCount(
							conversationID,
							conversationType
						);
						// 回执
						that.$store.state.zim.sendConversationMessageReceiptRead(
							conversationID,
							0
						);
					});
			},

			// 获取更多历史记录
			moreMessage() {
				// 后续分页获取时，nextMessage 为当前获取到的消息列表的第一条消息
				this.historyConfig.nextMessage = this.curMessageList[0];
				this.$store.state.zim
					.queryHistoryMessage(
						this.conversationID,
						0,
						this.historyConfig
					)
					.then(({
						messageList
					}) => {
						this.curMessageList.unshift(...messageList);
					});
			},

			afterRead() {

			},

			// 显示加号操作栏
			showUp() {
				this.upShow = !this.upShow

			},

			// 滚动到底部
			setScrollTop() {
				this.$nextTick(() => {
					uni.createSelectorQuery().in(this).select('.dialogue-box-content').boundingClientRect((
						res) => {
						console.log(res, 'res')
						if (res.height > 0) {
							this.scrollTop = res.height;
						}
					}).exec()
				})

			},

			//图片上传
			ChooseImage() {
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], //从相册选择
					success: (res) => {
						console.log('ChooseImage', res)
						if (res.tempFilePaths.length > 0) {
							this.imgUpload(res.tempFilePaths[0]);
							uni.showLoading({
								title: '上传中'
							});
						}
					}
				});
			},
			//获取OSS图片数据
			imgUpload(img) {
				homeApi.uploadImg(img).then(res => {
					uni.hideLoading();
					if (res.code === 1) {
						this.imgUrl = res.data.fullurl
						this.sendMessage(11)
					} else {
						this.$common.msgShow(res.msg);
					}
				})
			},

			// 关闭弹窗
			close() {
				this.shopShow = false;
				this.orderShow = false;
				this.shopPage = 1;
				this.shopList = []
				this.orderList = []
			},

			// 打开商品弹窗
			async shopOpen() {
				const res = await sApi.shop_manager_list({
					page: this.shopPage++,
					pagesize: 10,
					status: 1,
				})
				if (res.code == 1) {
					this.shopList.push(...res.data)
				}
			},

			// 打开订单弹窗
			async orderOpen() {
				const res = await sApi.getuserallorder({
					page: this.shopPage++,
					pagesize: 10,
					status: 0,
					user_id: this.conversationID
				})
				if (res.code == 1) {
					this.orderList.push(...res.data)
				}
			},

			async xg(index) {
				if (this.orderIndex == index) {
					const res = await sApi.getService_order_edit({
						money: Number(this.orderList[index].money),
						order_id: this.orderList[index].id
					})
					if (res.code == 1) {
						uni.showToast({
							title: '修改成功'
						})
						this.orderIndex = null
					}
				} else {
					this.orderIndex = index
				}
			}

		}
	}
</script>

<style lang="scss" scoped>
	.chat-list {
		overflow-anchor: none;
	}

	.chat-input {
		bottom: 0;
		position: fixed;
		left: 0;
		background-color: #fff;
		width: 750rpx;

		.wechat-area {
			padding: 0 25rpx;
			height: 88rpx;
			width: 100%;
			background-color: #EEF1F6;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.left-area {
				display: flex;
				align-items: center;

				.wechat-img {
					width: 35rpx;
					height: 35rpx;
					margin-left: 17rpx;
				}

				.wechat-text {
					margin-left: 10rpx;
					font-size: 24rpx;
					color: #333;
				}
			}

			.right-area {
				width: 102rpx;
				height: 41rpx;
				border: 2rpx solid #0B95FA;
				display: flex;
				align-items: center;
				justify-content: center;
				color: #0B95FA;
				font-size: 20rpx;
				border-radius: 500rpx;
			}
		}

		.input {
			width: 100%;
			box-sizing: border-box;
			display: flex;
			align-items: center;
			padding: 16rpx 30rpx 44rpx;
		}

		input {
			width: 470rpx;
			height: 70rpx;
			background: #F6F6F6;
			border-radius: 168rpx;
		}

		.but {
			width: 100rpx;
			height: 63rpx;
			line-height: 63rpx;
			color: #fff;
			text-align: center;
			border-radius: 8rpx;
			background-color: #0177FD;
		}

		.up {
			height: 180rpx;

			.grid-text {
				font-size: 22rpx;
				text-align: center;
			}
		}
	}

	.shop-list {
		.shop-title {
			text-align: center;
			padding-bottom: 21rpx;
			padding-top: 27rpx;
			font-size: 38rpx;
			font-weight: 500;
			color: #333333;
		}
	}

	.shop-item {
		display: flex;
		align-items: center;
		background: #FFFFFF;
		border-radius: 20rpx;
		width: 690rpx;
		height: 159rpx;
		margin: 13rpx auto;
		padding-left: 27rpx;

		image {
			width: 110rpx;
			height: 110rpx;
			border-radius: 10rpx;
			margin-right: 28rpx;
		}

		.info {
			width: 394rpx;
			font-size: 30rpx;
			font-weight: 500;
			color: #333333;

			.text {
				padding-top: 16rpx;
				font-size: 24rpx;
				font-weight: 400;
				color: #999999;
				display: flex;
				align-items: center;

				.xg {
					width: 67rpx;
					height: 34rpx;
					line-height: 34rpx;
					text-align: center;
					border-radius: 4rpx;
					margin-left: 25rpx;
					border: 1rpx solid #0177FD;
					font-size: 22rpx;
					color: #0177FD;
				}
			}
		}

		.money {
			text-align: center;

			view {
				font-size: 24rpx;
				color: #333333;
				padding-bottom: 20rpx;
				text-align: center;
			}
		}
	}

	.history {
		width: 140rpx;
		padding-top: 30rpx;
		margin: 0 auto;
	}
</style>